package com.luyuan.web.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.springframework.util.Assert;

import com.ruijie.foundation.bo.EntityObject;
import com.ruijie.foundation.service.Repository;
import com.ruijie.util.BeanUtils;
import com.ruijie.util.StringUtils;

/**
 * <p>Title: Module Information         </p>
 * <p>Description: Function Description </p>
 * <p>Copyright: Copyright (c) 2008     </p>
 * <p>Company: Ruijie Co., Ltd.         </p>
 * <p>Create Time: 2008-9-23              </p>
 * @author Anders
 * <p>Update Time:                      </p>
 * <p>Updater:                          </p>
 * <p>Update Comments:                  </p>
 */
public class EntityConverterAdapter implements Converter {

    private static final String DEFAULT_CONVERTER_PROPERTY = "id";

    private Repository<? extends EntityObject> repository;

    private String converterProperty = DEFAULT_CONVERTER_PROPERTY;

    public EntityConverterAdapter(Repository<? extends EntityObject> repository) {
        this(repository, DEFAULT_CONVERTER_PROPERTY);
    }

    public EntityConverterAdapter(Repository<? extends EntityObject> repository, String converterProperty) {
        Assert.notNull(repository);
        Assert.hasText(converterProperty);
        this.repository = repository;
        this.converterProperty = converterProperty;
    }

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {
        if (StringUtils.hasText(value)) {
            if (DEFAULT_CONVERTER_PROPERTY.equals(converterProperty)) {
                // ID 从get方法中取
                return repository.safeGet(value);
            }

            return repository.findUniqueBy(converterProperty, value);
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object object) {
        if (object == null) {
            return null;
        }
        Object value = null;
        try {
            value = BeanUtils.forceGetProperty(object, converterProperty);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        return value != null ? value.toString() : null;
    }
}
